package com.lhcai.classify.bfs;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 279.完全平方数
 *
 * @author liuhuaicai
 * @create 2024-05-30 21:51
 */
public class LC279 {
    public int numSquares(int n) {
        Queue<Integer> queue = new LinkedList<>();
        HashSet<Integer> set = new HashSet<>();
        int res = 0;
        queue.offer(0);
        while (!queue.isEmpty()) {
            res++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Integer cur = queue.poll();
                int j = 1;
                while (cur + j * j <= n) {// 平方和小于目标数字的都是节点的相邻节点
                    int temp = cur + j * j;
                    if (temp == n) {
                        return res;
                    }
                    j++;
                    if (set.contains(temp)) {
                        continue;
                    }
                    queue.offer(temp);
                    set.add(temp);//set用作记录路径
                }
            }

        }
        return -1;
    }
}
